package homework.day06;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 改正下面程序的错误,使得程序可以正常运行
 * 并能够正常的接收客户端发送的消息
 * @author Xiloer
 *
 */
public class Server {
	private ServerSocket server;
	
	public Server() {
		try {
			System.out.println("正在启动服务端");
			server = new ServerSocket(8088);
			System.out.println("服务端启动完毕");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void start(){
		try {
			while (true) {
				System.out.println("等待客户端连接...");
				Socket socket = server.accept();
				System.out.println("一个客户端连接了!");

//				实例化线程任务
				ClientHander handler = new ClientHander(socket);
//				创建线程执行该任务
				Thread t = new Thread(handler);
				t.start();

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	public static void main(String[] args) {
		Server server = new Server();
		server.start();
	}

	private class ClientHander implements Runnable{
		private Socket socket;
		private String host;

		public ClientHander(Socket socket) {
			this.socket = socket;
			host =socket.getInetAddress().getHostAddress();
		}

		public void run(){
			try {
				InputStream in = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(in,"UTF-8");
				BufferedReader br = new BufferedReader(isr);

				String line;
				while ((line = br.readLine())!=null){
					System.out.println(host+"说:"+line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}






